package com.prb.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截验证
 */
public class JurInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        System.out.println("request url is : " + request.getRequestURI());

        //校验是否存在登录cookie
        if(!checkLoginCookie(request)){
            //未登录,返回登录页面
            response.sendRedirect("/login/page");
            return false;
        }

        return true;
    }

    private boolean checkLoginCookie(HttpServletRequest request) {

        String sessionToken = (String) request.getSession().getAttribute("token");

        //服务器token 为空 ， 说明未登录
        if(sessionToken == null){
            return false;
        }

        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {
            //cookie 与 服务器 token 相同 登录成功
            if(cookie.getValue().equals(sessionToken)){
                return true;
            }
        }
        //cookie 与 服务器token 不相同 ， 未登录
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("post handler---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println("after completion -----------");
    }
}
